<template>
  <div>
    <basic-container>
      <avue-form :option="option" v-model="form" @tab-click="handleTabClick" @submit="handleSubmit"></avue-form>
    </basic-container>
    <el-dialog title="验证码" v-if="dialogVisible" :visible.sync="dialogVisible" append-to-body width="550px">
      <el-form :model="notBlankForm">
        <el-form-item prop="smsCode" :rules="[{ required: true, message: '验证码不能为空'}]">
          <el-input v-model.trim="notBlankForm.smsCode" placeholder="验证码" maxlength="6">
            <template slot="append">
              <el-button class="btnCode" type="primary" @click="signing()" :disabled="mBtn">
                <span v-show="!mBtn">获取验证码</span>
                <span v-show="mBtn">重新发送{{second}}S</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickNotBlank">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import option from "@/option/user/info";
  import {getUserInfo, updateInfo, updatePassword} from "@/api/system/user";
  import md5 from 'js-md5';
  import func from "@/util/func";
  import { getSmsCodeInner, updatePayPwd } from "@/api/rb-service/forgetPassword/forgetPassword";
  import {mapGetters} from "vuex";


  export default {
    data() {
      var oldNotBlank = (rule, value, callback)=>{
        if(this.index == 2){
          if (value === '') {
            callback(new Error('请输入二级密码'));
          } else if (value !== this.form.oldNotBlank) {
            callback(new Error('两次输入二级密码密码不一致!'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
      var newNotBlank = (rule, value, callback)=>  {
        if(this.index == 2){
          if (value === '') {
            callback(new Error('请再次输入二级密码码'));
          } else if (value !== this.form.oldNotBlank) {
            callback(new Error('两次输入二级密码密码不一致!'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
      return {
        index: 0,
        option: {
          tabs: true,
          tabsActive: 1,
          group: [
            {
              label: '个人信息',
              prop: 'info',
              column: [{
                label: '头像',
                type: 'upload',
                listType: 'picture-img',
                propsHttp: {
                  res: 'data',
                  url: 'link',
                },
                canvasOption: {
                  text: ' ',
                  ratio: 0.1
                },
                action: '/api/blade-resource/oss/endpoint/put-file',
                tip: '只能上传jpg/png用户头像，且不超过500kb',
                span: 12,
                row: true,
                prop: 'avatar'
              }, {
                label: '姓名',
                span: 12,
                row: true,
                prop: 'realName'
              }, {
                label: '用户名',
                span: 12,
                row: true,
                prop: 'name'
              }, {
                label: '手机号',
                span: 12,
                row: true,
                prop: 'phone'
              }, {
                label: '邮箱',
                prop: 'email',
                span: 12,
                row: true,
              }]
            },
            {
              label: '修改密码',
              prop: 'password',
              column: [{
                label: '原密码',
                span: 12,
                row: true,
                type: 'password',
                prop: 'oldPassword'
              }, {
                label: '新密码',
                span: 12,
                row: true,
                maxlength: 15,
                rules: [{ pattern:/^[a-zA-Z0-9]{5,15}$/, message: '密码5-15位，由英文、数字组成', trigger: 'blur' }],
                type: 'password',
                prop: 'newPassword'
              }, {
                label: '确认密码',
                span: 12,
                row: true,
                maxlength: 15,
                rules: [{ pattern:/^[a-zA-Z0-9]{5,15}$/, message: '密码5-15位，由英文、数字组成', trigger: 'blur' }],
                type: 'password',
                prop: 'newPassword1'
              }]
            },
            {
              label: '二级密码',
              prop: 'twoPwd',
              labelWidth:'120',
              column: [{
                label: '手机号',
                span: 12,
                row: true,
                readonly:true,
                prop: 'phone'
              }, 
              {
                label: '二级密码',
                span: 12,
                row: true,
                maxlength: 6,
                rules: [
                  { pattern:/^[0-9]{6}$/, message: '密码由6位数字组成', trigger: ['blur','change'] },
                  { required: true, validator: oldNotBlank, trigger: ['blur','change'] }
                ],
                type: 'password',
                prop: 'oldNotBlank'
              }, {
                label: '确认二级密码',
                span: 12,
                row: true,
                maxlength: 6,
                rules: [
                  { pattern:/^[0-9]{6}$/, message: '密码由6位数字组成', trigger: ['blur','change'] },
                  { required: true, validator: newNotBlank, trigger: ['blur','change'] }
                ],
                type: 'password',
                prop: 'newNotBlank'
              }]
            }
          ]
        },
        form: {},
        dialogVisible: false,
        notBlankForm:{
          smsCode:''
        },
        mBtn:false,
        second:0,
        timer:null,
        timeStamp:'',
        sign:''
      };
    },
    computed: {
      ...mapGetters(["tenantId"])
    },
    created() {
      if(this.$route.query.index){
        this.index = func.toInt(this.$route.query.index);
        this.option.tabsActive = this.index + 1;

        this.handleWitch();
      }else{
        this.handleWitch();
      }
    },
    methods: {
      /**
       * @func 返回页面
       * @desc 返回页面 goBack
       * */
      goBack() {
        this.$router.$avueRouter.closeTag();
        this.$router.back();
      },
      // 二级密码提交
      clickNotBlank(){
        let param ={
         payPassword:this.form.newNotBlank,
         smsCode:this.notBlankForm.smsCode
        }
        updatePayPwd(param).then((res)=>{
            this.$message({
              type: "success",
              message: res.data.msg
            });
            this.mBtn = false;
            clearInterval(this.timer);
            this.timer = null;
            this.dialogVisible = false;
            this.goBack()
        }, error => {
            window.console.log(error);
          })
      },
      /* 获取验证码 */
      signing(){
        // 获取时间戳
        this.timeStamp=Date.now();
        // RuiSY+时间戳+手机号 md5加密 传sign
        this.sign=md5('RuiSY'+this.timeStamp+this.form.phone);
        let param ={
          smsCodeType:'9',
          mobile:this.form.phone,
          tenantId:this.tenantId,
          sign:this.sign,
          timeStamp:this.timeStamp
        }
        getSmsCodeInner(param).then(()=>{},error=>{
          window.console.log(error);
          this.mBtn = false;
          clearInterval(this.timer);
          this.timer = null;
          this.notBlankForm.smsCode="";
        })
        // 发送验证码倒计时
        if (!this.timer) {
          this.second = 90;
          this.mBtn = true;
          this.timer = setInterval(() => {
            if (this.second > 0 && this.second <= 90) {
              this.second--;
            } else {
              this.mBtn = false;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000);
        }
      },
      handleSubmit(form, done) {
        if (this.index === 0) {
          updateInfo(form).then(res => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "修改信息成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
            done();
          }, error => {
            window.console.log(error);
            done();
          })
        } else if(this.index ===1) {
          updatePassword(md5(form.oldPassword), md5(form.newPassword), md5(form.newPassword1)).then(res => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "修改密码成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
            done();
          }, error => {
            window.console.log(error);
            done();
          })
        } else {
          done();
          this.dialogVisible = true;
        }
      },
      handleWitch() {
        if (this.index === 0) {
          getUserInfo().then(res => {
            const user = res.data.data;
            this.form = {
              id: user.id,
              avatar: user.avatar,
              name: user.name,
              realName: user.realName,
              phone: user.phone,
              email: user.email
            }
          });
        }else if (this.index === 2) {
          getUserInfo().then(res => {
            const user = res.data.data;
            this.form = {
              phone: user.account
            }
          });
        }
      },
      handleTabClick(tabs) {
        this.index = func.toInt(tabs.index);
        this.handleWitch();
      }
    }
  };
</script>

<style lang="scss" scoped>
/deep/ .el-input-group__append{
  background: #409eff;
  color: #fff;
}
.btnCode{
  width: 100px;
  border-radius: 0;
  padding-left: 0;
  padding-right: 0;
}
</style>
